<template>
  <view class="home-page">
    <!-- 状态栏（由系统自动填充） -->
    <view class="status-bar">
      <!-- 系统会自动填充状态栏 -->
    </view>
    
    <!-- 顶部品牌区域 -->
    <view class="brand-section">
      <text class="brand-name">金牌涛</text>
      <text class="brand-subtitle">红木家具交易平台</text>
    </view>
    
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-icons type="search" size="18" color="#999" />
      <input 
        class="search-input" 
        placeholder="搜索" 
        placeholder-style="color: #999;"
        @confirm="handleSearch"
      />
    </view>
    
    <!-- 分类导航 -->
    <scroll-view class="category-scroll" scroll-x>
      <view 
        v-for="(category, index) in categories" 
        :key="index"
        class="category-item"
        :class="{ active: activeCategory === category.value }"
        @click="changeCategory(category.value)"
      >
        {{ category.label }}
      </view>
    </scroll-view>
    
    <!-- 推荐标题 -->
    <view class="section-title">
      <text>推荐</text>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <uni-icons type="spinner-cycle" size="30" color="#8B4513" class="spinner" />
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 错误提示 -->
    <view v-else-if="error" class="error-container">
      <uni-icons type="close-circle" size="40" color="#e64340" />
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="loadFurnitureFromLocal">重试</button>
    </view>
    
    <!-- 家具列表 -->
    <view v-else class="furniture-list">
      <view 
        v-for="(item, index) in furnitureList" 
        :key="item._id"
        class="furniture-card"
        @click="navigateToDetail(item._id)"
      >
        <!-- 使用正确的图片路径占位符 -->
        <image 
          :src="item.imageUrl" 
          class="furniture-image" 
          mode="aspectFill" 
          v-if="item.imageUrl"
        />
        <view v-else class="image-placeholder">
          <uni-icons type="image" size="40" color="#ccc" />
        </view>
        <view class="furniture-info">
          <text class="furniture-name">{{ item.name }}</text>
          <view class="price-row">
            <text class="price">¥{{ item.price }}</text>
            <text class="sales">{{ item.sales }}人付款</text>
          </view>
          <view class="tags" v-if="item.tags && item.tags.length">
            <text v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="tag">
              {{ tag }}
            </text>
          </view>
        </view>
      </view>
      
      <!-- 空状态提示 -->
      <view v-if="furnitureList.length === 0" class="empty-container">
        <uni-icons type="info" size="40" color="#ccc" />
        <text class="empty-text">暂无家具数据</text>
        <button class="add-btn" @click="navigateToAdd">添加家具</button>
      </view>
    </view>
    
    <!-- 底部导航 -->
    <view class="tabs-bar">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: activeTab === tab.path }"
        @click="switchTab(tab.path)"
      >
        <image 
          :src="activeTab === tab.path ? tab.activeIcon : tab.icon" 
          class="tab-icon"
        />
        <text class="tab-text">{{ tab.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeCategory: 'all',
      categories: [
        { label: '沙发', value: 'sofa' },
        { label: '橱柜', value: 'cabinet' },
        { label: '屏风', value: 'screen' },
        { label: '架次', value: 'shelf' },
        { label: '桌椅', value: 'table' },
        { label: '床具', value: 'bed' },
        { label: '全部', value: 'all' }
      ],
      furnitureList: [], // 初始化为空数组，从本地数据库加载
      tabs: [
        { text: "主页", path: "/pages/home/index", icon: "/static/tabs/home.png", activeIcon: "/static/tabs/home-active.png" },
        { text: "发现", path: "/pages/discover/discover", icon: "/static/tabs/discover.png", activeIcon: "/static/tabs/discover-active.png" },
        { text: "库存", path: "/pages/inventory/index", icon: "/static/tabs/inventory.png", activeIcon: "/static/tabs/inventory-active.png" },
        { text: "店铺", path: "/pages/store/store", icon: "/static/tabs/shop.png", activeIcon: "/static/tabs/shop-active.png" },
        { text: "我", path: "/pages/profile/index", icon: "/static/tabs/profile.png", activeIcon: "/static/tabs/profile-active.png" }
      ],
      activeTab: "/pages/home/index",
      loading: true, // 加载状态
      error: null // 错误信息
    }
  },
  onLoad() {
    // 页面加载时从本地数据库加载家具数据
    this.loadFurnitureFromLocal();
  },
  onShow() {
    // 页面显示时刷新数据（从其他页面返回时可能数据有变化）
    this.loadFurnitureFromLocal();
  },
  methods: {
    // 从本地数据库加载家具数据
    loadFurnitureFromLocal() {
      this.loading = true;
      this.error = null;
      
      try {
        // 从本地存储获取家具数据
        const furnitureData = uni.getStorageSync('furniture_data');
        
        if (furnitureData && furnitureData.length > 0) {
          this.furnitureList = furnitureData;
          console.log('家具数据加载成功:', this.furnitureList);
          
          // 检查图片路径
          this.checkImagePaths();
        } else {
          console.warn('本地家具数据为空，使用默认数据');
          // 使用默认数据
          this.useDefaultData();
        }
      } catch (e) {
        console.error('加载家具数据失败:', e);
        this.error = '加载数据失败，请重试';
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 使用默认数据
    useDefaultData() {
      this.furnitureList = [
        {
          _id: '5',
          name: '国标红木黑酸枝新中式沙发',
          price: '22998.66',
          sales: 7,
          imageUrl: '/static/home_furniture/sofa.jpg',
          tags: ['国标红木', '黑酸枝', '新中式'],
          description: '精选黑酸枝木料，传统工艺精制而成的新中式风格沙发',
          category: '沙发',
          material: '黑酸枝',
          style: '新中式'
        },
        {
          _id: '6',
          name: '红木新中式红木古架多宝阁酸枝木客厅展示柜',
          price: '3268.66',
          sales: 35,
          imageUrl: '/static/home_furniture/cabinet.jpg',
          tags: ['酸枝木', '珠清古典', '仿红木家具'],
          description: '多宝阁设计，用于客厅展示收藏品',
          category: '架次',
          material: '酸枝木',
          style: '明清古典'
        },
        {
          _id: '7',
          name: '红木酒柜实木置物中式南美酸枝木',
          price: '11970',
          sales: 0,
          imageUrl: '/static/home_furniture/wine-cabinet.jpg',
          tags: ['植物花卉', '可移动', '明清古典'],
          description: '中式南美酸枝木酒柜，植物花卉雕刻精美',
          category: '橱柜',
          material: '南美酸枝木',
          style: '明清古典'
        },
        {
          _id: '8',
          name: '红木家具餐厅酒柜中式酒架墙壁柜',
          price: '31160',
          sales: 0,
          imageUrl: '/static/home_furniture/wine-rack.jpg',
          tags: ['植物花卉', '可移动', '明清古典'],
          description: '中式酒架墙壁柜，兼具实用与美观',
          category: '橱柜',
          material: '南美酸枝木',
          style: '明清古典'
        }
      ];
    },
    
    // 添加图片路径检查方法
    checkImagePaths() {
      this.furnitureList.forEach(item => {
        if (!item.imageUrl) {
          console.warn(`商品 ${item.name} 缺少图片路径`);
          item.imageUrl = null;
        }
      });
    },
    
    // 修改了方法名和添加了日志输出
    changeCategory(value) {
      console.log('切换分类:', value);
      this.activeCategory = value;
      
      // 实际项目中根据分类筛选数据
      // this.filterByCategory(value);
    },
    
    handleSearch(e) {
      const keyword = e.detail.value;
      if (keyword) {
        console.log('执行搜索:', keyword);
        // 实际项目中执行搜索
        // this.searchFurniture(keyword);
      }
    },
    
    // 跳转到商品详情页
    navigateToDetail(id) {
      console.log('跳转到商品详情:', id);
      
      // 使用正确的路径
      uni.navigateTo({
        url: `/pages/furniture/detail?id=${id}`
      });
    },
    
    // 跳转到添加家具页
    navigateToAdd() {
      uni.navigateTo({
        url: '/pages/furniture/add'
      });
    },
    
    switchTab(path) {
      console.log('切换到标签页:', path);
      this.activeTab = path;
      uni.switchTab({
        url: path
      });
    }
  }
}
</script>

<style lang="scss">
.home-page {
  padding: 10rpx 15rpx 120rpx;
  background-color: #fff;
}

.status-bar {
  height: var(--status-bar-height);
}

.brand-section {
  padding: 20rpx 0 15rpx;
  text-align: center;
  
  .brand-name {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    display: block;
  }
  
  .brand-subtitle {
    font-size: 26rpx;
    color: #666;
    display: block;
  }
}

.search-bar {
  display: flex;
  align-items: center;
  height: 70rpx;
  background-color: #f8f8f8;
  border-radius: 35rpx;
  padding: 0 25rpx;
  margin-bottom: 20rpx;
  
  .search-input {
    flex: 1;
    height: 100%;
    padding-left: 15rpx;
    font-size: 28rpx;
  }
}

.category-scroll {
  white-space: nowrap;
  padding: 25rpx 0;
  overflow-x: auto;
  
  .category-item {
    display: inline-block;
    padding: 12rpx 30rpx;
    margin-right: 15rpx;
    background-color: #f8f8f8;
    border-radius: 30rpx;
    font-size: 28rpx;
    
    &.active {
      background-color: #8B4513;
      color: #fff;
    }
  }
}

.section-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  padding: 20rpx 10rpx;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 20rpx;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
  
  .spinner {
    animation: rotate 1s linear infinite;
  }
  
  .loading-text {
    font-size: 28rpx;
    color: #666;
    margin-top: 20rpx;
  }
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
  
  .uni-icons {
    margin-bottom: 20rpx;
  }
  
  .error-text {
    font-size: 28rpx;
    color: #e64340;
    margin-bottom: 30rpx;
  }
  
  .retry-btn {
    width: 200rpx;
    height: 70rpx;
    line-height: 70rpx;
    background-color: #5c3c1c;
    color: white;
    border-radius: 35rpx;
    font-size: 28rpx;
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;
  
  .uni-icons {
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 30rpx;
  }
  
  .add-btn {
    width: 200rpx;
    height: 70rpx;
    line-height: 70rpx;
    background-color: #5c3c1c;
    color: white;
    border-radius: 35rpx;
    font-size: 28rpx;
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.furniture-list {
  .furniture-card {
    margin-bottom: 25rpx;
    border-radius: 8rpx;
    overflow: hidden;
    background-color: #fff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .furniture-image,
    .image-placeholder {
      width: 100%;
      height: 350rpx;
      background-color: #f8f8f8;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .furniture-info {
      padding: 20rpx;
      
      .furniture-name {
        font-size: 30rpx;
        color: #333;
        line-height: 1.4;
        margin-bottom: 15rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
      
      .price-row {
        display: flex;
        justify-content: space-between;
        
        .price {
          font-size: 32rpx;
          color: #e64340;
          font-weight: bold;
        }
        
        .sales {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .tags {
        display: flex;
        flex-wrap: wrap;
        margin-top: 15rpx;
        
        .tag {
          font-size: 24rpx;
          color: #8B4513;
          background-color: #fcf8e3;
          padding: 4rpx 15rpx;
          border-radius: 4rpx;
          margin-right: 10rpx;
          margin-bottom: 8rpx;
        }
      }
    }
  }
}

.tabs-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 15rpx 0;
  border-top: 1rpx solid #eee;
  z-index: 100;
  
  .tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 20%;
    
    .tab-icon {
      width: 45rpx;
      height: 45rpx;
    }
    
    .tab-text {
      font-size: 22rpx;
      margin-top: 6rpx;
      color: #999;
    }
    
    &.active .tab-text {
      color: #007AFF; /* 蓝色选中状态 */
      font-weight: bold;
    }
  }
}
</style>